package com.hanthink.system.service.impl.pc;

import java.util.List;

import com.hanthink.system.domain.pc.EmJobItem;
import com.hanthink.system.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hanthink.common.constant.BusinessConstants;
import com.hanthink.common.core.domain.entity.SysDept;
import com.hanthink.common.exception.CustomException;
import com.hanthink.common.utils.SerialNumberUtil;
import com.hanthink.common.utils.StringUtils;
import com.hanthink.system.domain.SysSerialNumber;
import com.hanthink.system.domain.SysSite;
import com.hanthink.system.domain.pc.EmEquip;
import com.hanthink.system.domain.pc.EmTaskPlan;
import com.hanthink.system.service.ISysDeptService;
import com.hanthink.system.service.impl.SysUserServiceImpl;
import com.hanthink.system.service.pc.IEmTaskPlanService;

/**
 * 任务计划Service业务层处理
 * 
 * @author hanthink
 * @date 2021-01-20
 */
@Service
public class EmTaskPlanServiceImpl implements IEmTaskPlanService {

	private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

	@Autowired
	private EmTaskPlanMapper emTaskPlanMapper;

	@Autowired
	private ISysDeptService deptService;

	@Autowired
	private EmEquipMapper emEquipMapper;

	@Autowired
	private SysDeptMapper deptMapper;

	@Autowired
	private SysSerialNumberMapper sysSerialNumberMapper;

	@Autowired
	private EmJobItemMapper jobItemMapper;

	/**
	 * 查询任务计划
	 * 
	 * @param siteKey 任务计划ID
	 * @return 任务计划
	 */
	@Override
	public EmTaskPlan selectEmTaskPlanById(String siteKey) {
		return emTaskPlanMapper.selectEmTaskPlanById(siteKey);
	}

	/**
	 * 查询任务计划列表
	 * 
	 * @param emTaskPlan 任务计划
	 * @return 任务计划
	 */
	@Override
	public List<EmTaskPlan> selectEmTaskPlanList(EmTaskPlan emTaskPlan) {
		return emTaskPlanMapper.selectEmTaskPlanList(emTaskPlan);
	}

	/**
	 * 新增任务计划
	 * 
	 * @param emTaskPlan 任务计划
	 * @return 结果
	 */
	@Override
	public int insertEmTaskPlan(EmTaskPlan emTaskPlan) {
		// 获取序列号
		SysSerialNumber serial = sysSerialNumberMapper.selectNextValue();
		String code = SerialNumberUtil.getSerialNumber(BusinessConstants.PLAN_TASK, serial.getNextValue(),
				serial.getToday());
		emTaskPlan.setPlanCode(code);
		// 校验数据库是否已存在
		EmTaskPlan queryEmTaskPlan = new EmTaskPlan();
		queryEmTaskPlan.setSiteKey(emTaskPlan.getSiteKey());
		queryEmTaskPlan.setPlanCode(emTaskPlan.getPlanCode());
		List<EmTaskPlan> list = emTaskPlanMapper.selectEmTaskPlanList(queryEmTaskPlan);
		if (list.size() > 0) {
			throw new CustomException("计划:" + emTaskPlan.getPlanCode() + "在系统中已存在，请核实");
		}
		// 校验设备在系统中是否存在
		EmEquip emEquip = new EmEquip();
		emEquip.setName(emTaskPlan.getEqKey());
		List<EmEquip> equipList = emEquipMapper.selectEmEquipList(emEquip);
		if (equipList.size() == 0) {
			throw new CustomException("设备条码:" + emTaskPlan.getEqKey() + "在系统中不存在，请核实");
		}
		// 校验部门信息在系统是否存在
		SysDept dept = new SysDept();
		dept.setParentId(Long.valueOf(emTaskPlan.getSiteKey()));
		dept.setDeptName(emTaskPlan.getDepartment());
		List<SysDept> deptList = deptMapper.selectDeptList(dept);
		if (deptList.size() == 0) {
			throw new CustomException("部门:" + emTaskPlan.getDepartment() + "在系统中不存在，请核实");
		}

		return emTaskPlanMapper.insertEmTaskPlan(emTaskPlan);
	}

	/**
	 * 修改任务计划
	 * 
	 * @param emTaskPlan 任务计划
	 * @return 结果
	 */
	@Override
	public int updateEmTaskPlan(EmTaskPlan emTaskPlan) {
		return emTaskPlanMapper.updateEmTaskPlan(emTaskPlan);
	}

	/**
	 * 批量删除任务计划
	 * 
	 * @param siteKeys 需要删除的任务计划ID
	 * @return 结果
	 */
	@Override
	public int deleteEmTaskPlanByIds(String[] siteKeys) {
		return emTaskPlanMapper.deleteEmTaskPlanByIds(siteKeys);
	}

	/**
	 * 删除任务计划信息
	 * 
	 * @param siteKey 任务计划ID
	 * @return 结果
	 */
	@Override
	public int deleteEmTaskPlanById(String siteKey) {
		return emTaskPlanMapper.deleteEmTaskPlanById(siteKey);
	}

	@Override
	public List<SysSite> getSiteList() {
		return emTaskPlanMapper.getSiteList();
	}

	/**
	 * 导入数据
	 * 
	 * @param planList        计划数据列表
	 * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
	 * @param operName        操作用户
	 * @return 结果
	 */
	@Override
	public String importPlan(List<EmTaskPlan> planList, Boolean isUpdateSupport, String operName) {
		if (StringUtils.isNull(planList) || planList.size() == 0) {
			throw new CustomException("导入计划数据不能为空！");
		}
		int successNum = 0;
		int failureNum = 0;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		int currentRowNum = 0;
		for (EmTaskPlan plan : planList) {
			currentRowNum++;
			try {
				// 校验数据信息
				if (StringUtils.isEmpty(plan.getSiteKey())) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据 工厂不能为空");
					continue;
				} else if (StringUtils.isEmpty(plan.getEqKey())) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据设备编码不能为空");
					continue;
				} else if (StringUtils.isNull(plan.getCycle()) || !StringUtils.isNumeric(plan.getCycle().toString())) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据周期不能为空且只能为数字类型");
					continue;
				} else if (StringUtils.isEmpty(plan.getPlanType()) || !StringUtils.isNumeric(plan.getPlanType())) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据计划类型不能为空且只能为数字类型");
					continue;
				} else if (StringUtils.isEmpty(plan.getEqStatus()) || !StringUtils.isNumeric(plan.getEqStatus())) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据设备运行状态不能为空且只能为数字类型");
					continue;
				} else if (StringUtils.isEmpty(plan.getStatus()) || !StringUtils.isNumeric(plan.getStatus())) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据任务状态不能为空且只能为数字类型");
					continue;
				} else if (StringUtils.isEmpty(plan.getIsRepeat()) || !StringUtils.isNumeric(plan.getIsRepeat())) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据是否重复不能为空且只能为数字类型");
					continue;
				}
				// 事业部匹配
				SysDept hangame = new SysDept();
				hangame.setDeptName(plan.getHangameKey());
				List<SysDept> hangameList = deptService.selectDeptList(hangame);
				if (hangameList.size() == 0) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据事业部信息在系统中不存在，请核实");
					continue;
				}
				plan.setHangameKey(hangameList.get(0).getDeptId().toString());
				// 工厂匹配
				SysDept dept = new SysDept();
				dept.setParentId(hangameList.get(0).getDeptId());
				dept.setDeptName(plan.getSiteKey());
				List<SysDept> deptList = deptService.selectDeptList(dept);
				if (deptList.size() == 0) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据工厂信息在事业部中不存在，请核实");
					continue;
				}
				// 设备编码校验
				EmEquip emEquip = new EmEquip();
				emEquip.setName(plan.getEqKey());
				List<EmEquip> emEquips = emEquipMapper.selectEmEquipList(emEquip);
				if (emEquips.size() == 0) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据设备信息在系统中不存在，请核实");
					continue;
				}
				plan.setSiteKey(deptList.get(0).getDeptId().toString());

				plan.setCreateBy(operName);

				//校验任务点检项
				EmJobItem emJobItem = new EmJobItem();
				emJobItem.setHangameKey(plan.getHangameKey());
				emJobItem.setSiteKey(plan.getSiteKey());
				emJobItem.setEqKey(plan.getEqKey());
				emJobItem.setCycle(plan.getCycle());
				emJobItem.setItemType(plan.getPlanType());
				emJobItem.setDepartment(plan.getDepartment());
				List<EmJobItem> item = jobItemMapper.selectEmJobItemList(emJobItem);
				if (item.size() == 0) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据设备信息无点检项信息，请核实");
					continue;
				}

				EmTaskPlan queryPlan = new EmTaskPlan();
				queryPlan.setPlanCode(plan.getPlanCode());
				List<EmTaskPlan> plans = emTaskPlanMapper.selectEmTaskPlanList(queryPlan);
				if(plans.size() > 0 && isUpdateSupport){
					EmTaskPlan p = plans.get(0);
					plan.setUpdateBy(operName);
					plan.setId(p.getId());
					this.updateEmTaskPlan(plan);
					successNum++;
					successMsg.append("<br/>" + successNum + "、设备计划 " + plan.getEqKey() + " 更新成功");
				}else {
					plan.setCreateBy(operName);
					// 获取序列号
					SysSerialNumber serial = sysSerialNumberMapper.selectNextValue();
					String code = SerialNumberUtil.getSerialNumber(BusinessConstants.PLAN_TASK, serial.getNextValue(),
							serial.getToday());
					plan.setPlanCode(code);
					this.insertEmTaskPlan(plan);
					successNum++;
					successMsg.append("<br/>" + successNum + "、设备计划 " + plan.getEqKey() + " 导入成功");
				}

			} catch (Exception e) {
				failureNum++;
				String msg = "<br/>" + failureNum + "、设备计划" + plan.getEqKey() + " 导入失败：";
				failureMsg.append(msg + e.getMessage());
				log.error(msg, e);
			}
		}
		if (failureNum > 0) {
			failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
			throw new CustomException(failureMsg.toString());
		} else {
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
		}
		return successMsg.toString();
	}
}
